package com.witframework.dynoengine.render.page;

import java.sql.Types;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.witframework.core.persistence.JdbcTools;
import com.witframework.dynoengine.AbstractParamSetObject;
import com.witframework.dynoengine.MetaFactory;
import com.witframework.dynoengine.model.WitMetaColumn;
import com.witframework.dynoengine.model.WitMetaTable;
import com.witframework.dynoengine.render.ColumnComparator;
import com.witframework.dynoengine.render.MiniTemplator;
import com.witframework.dynoengine.render.Renderer;
import com.witframework.dynoengine.render.TempleteFactory;
import com.witframework.dynoengine.render.form.DateRender;
import com.witframework.dynoengine.render.form.FormFieldRender;
import com.witframework.dynoengine.render.form.InputRender;
import com.witframework.dynoengine.render.form.TextareaRender;
import com.witframework.dynoengine.render.selector.DefaultOptionSelectorRender;
import com.witframework.dynoengine.render.selector.SelectorRender;
import com.witframework.util.StringTools;

public class UpdateDataPageRender extends AbstractParamSetObject implements Renderer {	
	public String render() {	
		String tableId=(String)getParameter(Renderer.PARAM_tableId);
		String tableName=(String)getParameter(Renderer.PARAM_tableName);
		WitMetaTable mt=MetaFactory.getInstance().getMetaTableByName(tableName);
		tableName=(tableName==null?tableName=mt.getTableName():tableName.toUpperCase());
		HttpServletRequest httpRequest=(HttpServletRequest)getParameter(Renderer.PARAM_httpRequest);		
		//FIXME 去掉 刷新元数据缓存
		MetaFactory.getInstance().refresh();
		
		MiniTemplator templator=TempleteFactory.getInstance().getMiniTemplator("form/form.page");
		templator.setVariableOpt("tableName", tableName);
		templator.setVariableOpt("tableTitle", StringUtils.isNotEmpty(mt.getTableTitle())?mt.getTableTitle():tableName);
		templator.setVariableOpt("contextPath", httpRequest.getContextPath());
		templator.setVariableOpt("action", httpRequest.getParameter("action"));
		
		Map data=getData(tableName);
		List<WitMetaColumn> metColumnList=MetaFactory.getInstance().getMetaFileds(tableName);
		WitMetaColumn[] metColumns=metColumnList.toArray(new WitMetaColumn[0]);
		Arrays.sort(metColumns,new ColumnComparator());		
		if(templator.blockExists("form_column")){
			for(WitMetaColumn wmc:metColumns){
					Renderer render=null;
					String selectType=wmc.getSelectType();
					if(StringUtils.isEmpty(selectType)){
						int columnSize=wmc.getColumnSize();
						int columnType=wmc.getColumnType();
						if(Types.DATE==columnType||Types.TIMESTAMP==columnType||Types.TIME==columnType){
							render=new DateRender();					
						}else if(columnSize<80){
							render=new InputRender();							
						}else{
							render=new TextareaRender();
						}
						if(StringTools.parseBoolean(wmc.getIsPkey())||!StringTools.parseBoolean(wmc.getIsDisplayable()))
								render.setParameter(FormFieldRender.PARAM_type,"readonly");
						render.setParameter(FormFieldRender.PARAM_name, wmc.getColumnName());
						render.setParameter(FormFieldRender.PARAM_editable,wmc.getIsEditable());
						render.setParameter(FormFieldRender.PARAM_size,wmc.getColumnSize());
						render.setParameter(FormFieldRender.PARAM_tiptext, wmc.getTipText());
						render.setParameter(FormFieldRender.PARAM_validation, wmc.getValidation());			
						
						if(data!=null)
							render.setParameter(FormFieldRender.PARAM_value, data.get(wmc.getColumnName()));		
						
					}else if(selectType.equalsIgnoreCase("select")||selectType.equalsIgnoreCase("mselect")){
						render=new DefaultOptionSelectorRender();
						render.setParameter(SelectorRender.PARAM_parameter, wmc.getSelectParam());
						render.setParameter(FormFieldRender.PARAM_name, wmc.getColumnName());
						render.setParameter(FormFieldRender.PARAM_editable,wmc.getIsEditable());
						render.setParameter(FormFieldRender.PARAM_size,wmc.getColumnSize());
						render.setParameter(FormFieldRender.PARAM_tiptext, wmc.getTipText());
						render.setParameter(FormFieldRender.PARAM_validation, wmc.getValidation());	
					}else{
						
					}
					
					String columnFromField=render.render();
					templator.setVariableOpt("columnName", wmc.getColumnName());
					templator.setVariableOpt("columnTitle", StringUtils.isEmpty(wmc.getColumnTitle())?wmc.getColumnName():wmc.getColumnTitle());//
					templator.setVariableOpt("columnFromField", columnFromField);
					if(StringTools.parseBoolean(wmc.getIsPkey()) || !StringTools.parseBoolean(wmc.getIsNullable())){
							templator.setVariableOpt("mustFlag", "<font color=red>(*)</font>");
					}else{
						templator.setVariableOpt("mustFlag", "");
					}
					templator.addBlock("form_column");
			}
			
		}
		
		return templator.generateOutput();//StringTools.compressHtml(templator.generateOutput());
		
	}
	private String renderWithGroup(){		
		String tableName=(String)getParameter(Renderer.PARAM_tableName);
		WitMetaTable mt=MetaFactory.getInstance().getMetaTableByName(tableName);
		tableName=(tableName==null?tableName=mt.getTableName():tableName.toUpperCase());
		HttpServletRequest httpRequest=(HttpServletRequest)getParameter(Renderer.PARAM_httpRequest);		
		//FIXME 去掉 刷新元数据缓存
		MetaFactory.getInstance().refresh();		
		MiniTemplator templator=TempleteFactory.getInstance().getMiniTemplator("form/form.page","columnGroup");
		
		templator.setVariableOpt("tableName", tableName);
		templator.setVariableOpt("tableTitle", StringUtils.isNotEmpty(mt.getTableTitle())?mt.getTableTitle():tableName);
		templator.setVariableOpt("contextPath", httpRequest.getContextPath());
		templator.setVariableOpt("action", httpRequest.getParameter("action"));
		
		Map data=getData(tableName);
		List<WitMetaColumn> metColumnList=MetaFactory.getInstance().getMetaFileds(tableName);
		WitMetaColumn[] metColumns=metColumnList.toArray(new WitMetaColumn[0]);
		Arrays.sort(metColumns,new ColumnComparator());		
		if(templator.blockExists("form_fieldset")){//分组开始
			if(templator.blockExists("form_column")){
				for(WitMetaColumn wmc:metColumns){
						Renderer render=null;
						String selectType=wmc.getSelectType();
						if(StringUtils.isEmpty(selectType)){
							int columnSize=wmc.getColumnSize();
							int columnType=wmc.getColumnType();
							if(Types.DATE==columnType||Types.TIMESTAMP==columnType||Types.TIME==columnType){
								render=new DateRender();					
							}else if(columnSize<30){
								render=new InputRender();							
							}else{
								render=new TextareaRender();
							}
							if(StringTools.parseBoolean(wmc.getIsPkey())||!StringTools.parseBoolean(wmc.getIsDisplayable()))
									render.setParameter(FormFieldRender.PARAM_type,"readonly");
							render.setParameter(FormFieldRender.PARAM_name, wmc.getColumnName());
							render.setParameter(FormFieldRender.PARAM_editable,wmc.getIsEditable());
							render.setParameter(FormFieldRender.PARAM_size,wmc.getColumnSize());
							render.setParameter(FormFieldRender.PARAM_tiptext, wmc.getTipText());
							render.setParameter(FormFieldRender.PARAM_validation, wmc.getValidation());			
							
							if(data!=null)
								render.setParameter(FormFieldRender.PARAM_value, data.get(wmc.getColumnName()));		
							
						}else if(selectType.equalsIgnoreCase("select")||selectType.equalsIgnoreCase("mselect")){
							render=new DefaultOptionSelectorRender();
							render.setParameter(SelectorRender.PARAM_parameter, wmc.getSelectParam());
							render.setParameter(FormFieldRender.PARAM_name, wmc.getColumnName());
							render.setParameter(FormFieldRender.PARAM_editable,wmc.getIsEditable());
							render.setParameter(FormFieldRender.PARAM_size,wmc.getColumnSize());
							render.setParameter(FormFieldRender.PARAM_tiptext, wmc.getTipText());
							render.setParameter(FormFieldRender.PARAM_validation, wmc.getValidation());	
						}else{
							
						}
						
						String columnFromField=render.render();
						templator.setVariableOpt("columnName", wmc.getColumnName());
						templator.setVariableOpt("columnTitle", StringUtils.isEmpty(wmc.getColumnTitle())?wmc.getColumnName():wmc.getColumnTitle());//
						templator.setVariableOpt("columnFromField", columnFromField);
						if(StringTools.parseBoolean(wmc.getIsPkey()) || !StringTools.parseBoolean(wmc.getIsNullable())){
								templator.setVariableOpt("mustFlag", "<font color=red>(*)</font>");
						}else{
							templator.setVariableOpt("mustFlag", "");
						}
						templator.addBlock("form_column");
				}
				
			}//分组结束
			
		}	
		
		return templator.generateOutput();//StringTools.compressHtml(templator.generateOutput());
	}
	//查询当前记录的数据
	private Map getData(String tableName){
		HttpServletRequest httpRequest=(HttpServletRequest)getParameter(Renderer.PARAM_httpRequest);		
		//生成查询条件
		String sqlWhere="";
		String[] pks=MetaFactory.getInstance().getTablePK(tableName);
		for(String pkColumnName:pks){
			if(sqlWhere.length()>0) sqlWhere+=" AND ";
			sqlWhere+=pkColumnName+"=";
			WitMetaColumn wmc=MetaFactory.getInstance().getMetaFiled(tableName, pkColumnName);
			int columnType=wmc.getColumnType();
			String pkValue=httpRequest.getParameter(pkColumnName);		
			if(columnType==java.sql.Types.INTEGER||columnType==java.sql.Types.NUMERIC){
				sqlWhere+=pkValue;
			}else{
				sqlWhere+=" '"+pkValue+"' ";
			}
		}
		
		if(sqlWhere.length()>1){
			return JdbcTools.queryForMap("SELECT * FROM "+tableName+"  WHERE "+sqlWhere);
		}
		return null;
	}
}
